#include "userlib.h"

int ResultSet::nextid = 1;

void ResultSet::init(void)
{
	time_t t;
	struct tm tm;
	
	this->id = (nextid++);
	this->range = 0;
	t = time(0);
	if(t==-1)
		die("time");
	if( localtime_r(&t, &tm)==0 )
		die("localtime_r");
	this->h = tm.tm_hour;
	this->m = tm.tm_min;
}

ResultSet::ResultSet(unsigned long long val)
{
	init();
	this->source = FIND;
	this->value = val;
}

ResultSet::ResultSet(ResultSet *rs1, ResultSet *rs2)
{
	int ret;
	
	init();
	this->source = INTERSECT;
	this->r1 = rs1->id;
	this->r2 = rs2->id;
	list<struct Addr>::iterator i1 = rs1->addrs.begin(), i2 = rs2->addrs.begin();
	while(i1 != rs1->addrs.end() && i2 != rs2->addrs.end() ){
		ret = compareaddr( &(*i1), &(*i2) );
		if(ret<0)
			i1++;
		else if(ret>0)
			i2++;
		else{
			this->addrs.push_back(*i1);
			i1++; i2++;
		}
	}
}

void ResultSet::add(unsigned long offset)
{
	struct Addr a;
	if(range == 0){
		fprintf(stderr, "BUG: ResultSet->range == 0\n"); 
		exit(1);
	}else{
		a.pid = range->pid;
		a.addr = range->start + offset;
		this->addrs.push_back(a);
	}
}

void ResultSet::printinfo(void)
{
	printf("Result Set \"r%d\", %lu addrs, ", this->id, this->addrs.size() );
	if(this->source == FIND)
		printf("\"f %llu\", ", this->value);
	else if(this->source == INTERSECT)
		printf("\"^ r%d r%d\", ", this->r1, this->r2);
	printf("since %d:%d\n", this->h, this->m);
}

void ResultSet::printaddrs(void)
{
	list<struct Addr>::iterator it;
	struct Addr *a;
	if(this->addrs.size()){
		printf("%-6s address\n", "pid");
		for(it = this->addrs.begin(); it != this->addrs.end(); it++ ){
			a = &(*it);
			printf("%-6ld %lx\n", (long)a->pid, a->addr);
		}
	}
}
